package com.gin.kotlin.gf2gamecommunity.routes

import androidx.compose.animation.core.tween
import androidx.compose.animation.slideInHorizontally
import androidx.compose.animation.slideOutHorizontally
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.Person
import androidx.compose.material.icons.filled.Search
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavGraphBuilder
import androidx.navigation.compose.composable
import androidx.navigation.toRoute
import androidx.paging.compose.collectAsLazyPagingItems
import com.gin.kotlin.gf2gamecommunity.R
import com.gin.kotlin.gf2gamecommunity.base.composable.Loading
import com.gin.kotlin.gf2gamecommunity.base.composable.TabInfo
import com.gin.kotlin.gf2gamecommunity.base.composable.TabRowPager
import com.gin.kotlin.gf2gamecommunity.composable.FollowChip
import com.gin.kotlin.gf2gamecommunity.composable.TopicLazyColumn
import com.gin.kotlin.gf2gamecommunity.composable.UserAvatar
import com.gin.kotlin.gf2gamecommunity.navi.GF2Navigator
import com.gin.kotlin.gf2gamecommunity.viewmodel.SearchViewModel
import kotlinx.coroutines.launch
import kotlinx.serialization.Serializable


fun NavGraphBuilder.search(navigator: GF2Navigator) = composable<SearchRoute>(
    // 从屏幕右侧进入，持续500毫秒
    enterTransition = { slideInHorizontally(tween(500)) { it } },
    // 从屏幕右侧退出，持续500毫秒
    exitTransition = { slideOutHorizontally(tween(500)) { it } },
) {
    SearchComposable(route = it.toRoute(), navigator = navigator)
}

@Serializable
data class SearchRoute(val id: Int = 1)

@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun SearchComposable(route: SearchRoute, navigator: GF2Navigator, viewModel: SearchViewModel = viewModel()) {

    var keyword by remember { mutableStateOf("") }
    var text by remember { mutableStateOf("") }
    val tabState = rememberPagerState(pageCount = { 2 })
    val coroutineScope = rememberCoroutineScope()
    var expanded by remember { mutableStateOf(false) }
    val topicPagingItems = viewModel.topic.fetch(keyword).collectAsLazyPagingItems()
    val userPagingItems = viewModel.user.fetch(keyword).collectAsLazyPagingItems()
    val topicListState = rememberLazyListState()
    val userListState = rememberLazyListState()

    fun search(w: String) {
        keyword = w
        text = w
        expanded = false

        val pagingItems = if (tabState.currentPage == 0) topicPagingItems else userPagingItems
        val listState = if (tabState.currentPage == 0) topicListState else userListState

        // 刷新操作
        if (pagingItems.itemCount > 0) {
            pagingItems.refresh()
            coroutineScope.launch { listState.scrollToItem(0) }
        }

    }

    navigator.apply {
        Scaffold(
            topBar = {
                TopAppBar(navigationIcon = {
                    IconButton(onClick = { onPopBackStack() }) {
                        Icon(imageVector = Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "后退")
                    }
                }, actions = {
                    Box {
                        IconButton(onClick = { expanded = true }) {
                            Icon(painterResource(R.drawable.ic_hot_24), contentDescription = "热词选择")
                        }
                        DropdownMenu(expanded = expanded, onDismissRequest = { expanded = false }) {
                            val state = viewModel.hotWord.fetch().observeAsState()
                            val hotWord = state.value?.map { it.word }
                            hotWord?.onEach { DropdownMenuItem(text = { Text(it, fontSize = 22.sp) }, onClick = { search(it) }) } ?: Loading()
                        }
                    }

                    IconButton(onClick = { search(text) }) {
                        Icon(imageVector = Icons.Filled.Search, contentDescription = "搜索")
                    }
                }, title = { Text("搜索") })
            },
        ) { paddingValues ->
            Column(modifier = Modifier
                .padding(paddingValues)
                .fillMaxWidth()) {

                // 输入框及搜索按钮
                Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier
                    .fillMaxWidth()
                    .padding(8.dp), horizontalArrangement = Arrangement.End) {
                    TextField(value = text, onValueChange = { text = it }, label = { Text("请输入关键字") },
                        keyboardOptions = KeyboardOptions.Default.copy(imeAction = ImeAction.Search), keyboardActions = KeyboardActions(onSearch = { search(text) }),
                        modifier = Modifier.weight(1f))

                }


                TabRowPager(listOf(
                    TabInfo("主题", iconDrawable = R.drawable.ic_topic_24) {
                        TopicLazyColumn(lazyPagingItems = topicPagingItems, onNavigateToCommentList = { r -> onNavigateToCommentList(r) }, state = topicListState,
                            toppedTopics = null)
                    },
                    TabInfo("用户", iconVector = Icons.Filled.Person) {
                        LazyColumn(verticalArrangement = Arrangement.spacedBy(4.dp), state = userListState, modifier = Modifier.padding(8.dp)) {
                            items(userPagingItems.itemCount) { index ->
                                userPagingItems[index]?.apply {
                                    Row(verticalAlignment = Alignment.CenterVertically) {
                                        UserAvatar(avatar, modifier = Modifier
                                            .clip(CircleShape)
                                            .size(80.dp))
                                        Column(
                                            verticalArrangement = Arrangement.spacedBy(8.dp),
                                            modifier = Modifier.weight(1f),
                                        ) {
                                            Text(nickName, fontSize = 20.sp)
                                            Text("粉丝: $fansNum", modifier = Modifier.graphicsLayer { alpha = 0.7f })
                                        }
                                        FollowChip(uid, isFollow) { isFollow = it }
                                    }

                                }
                            }
                        }
                    },
                ), tabState = tabState)
            }

        }
    }
}

@Composable
private fun SearchTab() {

}
